package com.szsh.aiot.framework.config;

import com.szsh.aiot.hsm.utils.Hash163;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.function.Supplier;

@Configuration
public class CommonConfig {

    @Value("${hsm.interface.longtimeout}")
    public int longtimeout;

    @Value("${hsm.interface.shorttimeout}")
    public int shorttimeout;


    @Primary
    @Bean(name = "shorttimeout")
    public RestTemplate getRestTemplate(RestTemplateBuilder builder) {
        RestTemplate restTemplate = builder
                .requestFactory(HttpComponentsClientHttpRequestFactory.class)
                .additionalInterceptors(new LoggingRequestInterceptor())
                .setConnectTimeout(Duration.ofMillis(shorttimeout))
                .setReadTimeout(Duration.ofMillis(shorttimeout))
                .build();
        restTemplate.getMessageConverters().set(1,
                new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;

    }

    @Bean(name = "longtimeout")
    public RestTemplate longtimeoutRestTemplate(RestTemplateBuilder builder) {
        RestTemplate restTemplate = builder
                .requestFactory(HttpComponentsClientHttpRequestFactory.class)
                .additionalInterceptors(new LoggingRequestInterceptor())
                .setConnectTimeout(Duration.ofMillis(longtimeout))
                .setReadTimeout(Duration.ofMillis(longtimeout))
                .build();
        restTemplate.getMessageConverters().set(1,
                new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }

    @Bean(name = "superLongTimeoutRestTemplate")
    public RestTemplate restTemplate(RestTemplateBuilder builder, OkHttpClient okHttpClient) {
        Supplier<ClientHttpRequestFactory> requestFactory = () -> new OkHttp3ClientHttpRequestFactory(okHttpClient);

        RestTemplate restTemplate = builder
                .requestFactory(requestFactory)
                .additionalInterceptors(new LoggingRequestInterceptor())
                .build();

        restTemplate.getMessageConverters().set(1,
                new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
}
